import React, { useEffect, useState } from 'react';
import styles from './index.less';
import { DatePicker, Table, Select, Space } from 'antd';
import moment from 'moment';
import BarLine from '@/components/BarLine';
import { getFinance, getFinanceLine } from '@/api/services';
import * as echarts from 'echarts';

interface TProps {
    //   sourceData: RecordItem;
    getDate: (start: string, end: string) => void;
}

const { RangePicker } = DatePicker;

const Container: React.FC<TProps> = () => {
    const [opage, setOPage] = useState<number>(1);
    const [ipage, setIPage] = useState<number>(1);
    const [ototal, setOTotal] = useState(0);
    const [itotal, setITotal] = useState(0);
    const [incomeArray, setIncomeArray] = useState<any>([]);
    const [outcomeArray, setOutcomeArray] = useState<any>([]);
    const [outdata, setOutData] = useState<any>([]);
    const [indata, setInData] = useState<any>([]);
    const [year, setYear] = useState<any>('2024');
    const [type, setType] = useState<string>('支出');

    useEffect(() => {
        getFinance({
            type: type,
            page: type == '支出' ? opage : ipage,
            size: 5
        }).then((res: any) => {
            console.log(res);
            if (res.status == 200) {
                if (type == '支出') {
                    console.log(res.results);
                    setOutData(res.results);
                    setOTotal(res.length);
                }
                if (type == '收入') {
                    setInData(res.results);
                    setITotal(res.length);
                }
            }
        })
    }, [type, opage, ipage])

    useEffect(() => {
        getFinanceLine({
            year: year
        }).then((res: any) => {
            if (res.status == 200) {
                console.log(res)
                const iArray = res.incomeArr.map((item: any) => item.money);
                console.log(iArray);
                setIncomeArray(iArray);
                const oArray = res.outcomeArr.map((item: any) => item.money);
                console.log(oArray);
                setOutcomeArray(oArray);
            }
        })
    }, [year])

    useEffect(() => {
        initCharts();
    }, [outcomeArray])

    const handleChange = (value: string) => {
        // console.log(`selected ${value}`);
        setYear(value);
    };

    const formatDetail = (data: any) => {
        var dataArray = data.split("||");
        var result = "";

        // 遍历数组中的每一对数据
        for (var i = 0; i < dataArray.length; i += 2) {
            // 获取物品名称和数量
            var item = dataArray[i].trim();
            var quantity = dataArray[i + 1].trim();

            // 格式化为键值对的形式，并添加到结果中
            result += item + "：" + quantity;

            // 如果不是最后一对数据，添加逗号分隔符
            if (i < dataArray.length - 2) {
                result += ", ";
            }
        }

        return result;
    }


    const handleTableChange = (value: string) => {
        setIPage(1);
        setOPage(1);
        setType(value);
        
    }
    const outcolumns = [

        {
            title: '支出金额',
            dataIndex: 'buy_money',
        },
        {
            title: '明细',
            dataIndex: 'buy_detail',
            render: (_: any, record: any) => (
                <div>
                    <Space direction="vertical" size="middle" style={{ display: 'flex' }}>
                        {formatDetail(record.buy_detail).split(',').map((item: any, index: number) => (
                            <span key={index}>{item}</span>
                        ))}
                    </Space>
                </div>
            )
        },
        {
            title: '采购时间',
            dataIndex: 'buy_posttime',
        },
        {
            title: '类型',
            dataIndex: 'buy_type',
        },
        {
            title: '采购员',
            dataIndex: 'buyerName',
        },
        {
            title: '仓库管理员',
            dataIndex: 'storerName'
        },


    ];

    const incolumns = [
        {
            title: '收入金额',
            dataIndex: 'order_money',
        },
        {
            title: '明细',
            dataIndex: 'order_detail',
            render: (_: any, record: any) => (
                <div>
                    <Space direction="vertical" size="middle" style={{ display: 'flex' }}>
                        {formatDetail(record.order_detail).split(',').map((item: any, index: number) => (
                            <span key={index}>{item}</span>
                        ))}
                    </Space>
                </div>
            )

        },
        {
            title: '采购时间',
            dataIndex: 'order_posttime',
        },
        {
            title: '类型',
            dataIndex: 'order_type',
        },
        {
            title: '生产计划员',
            dataIndex: 'plannerName',
        },
        {
            title: '负责经理',
            dataIndex: 'directorName'
        },


    ];

    const initCharts = () => {
        var myChart = echarts.init(document.getElementById('main'));
        const option = {
            title: {
                text: '财务收支分析'
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                    label: {
                        backgroundColor: '#6a7985'
                    }
                }
            },
            legend: {
                data: ['收入', '支出']
            },
            toolbox: {
                feature: {
                    saveAsImage: {}
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: [
                {
                    type: 'category',
                    boundaryGap: false,
                    data: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
                }
            ],
            yAxis: [
                {
                    type: 'value'
                }
            ],
            series: [
                {
                    name: '收入',
                    type: 'line',
                    data: incomeArray
                },
                {
                    name: '支出',
                    type: 'line',
                    data: outcomeArray
                },

            ]
        };
        myChart.setOption(option);
    }

    const paginationConfig = {
        current: opage,
        total: ototal,
        pageSize: 5,
        onChange: (page: number, pageSize?: number) => {
            setOPage(page);
        },
        showTotal: (total: number, range: [number, number]) => `共 ${total} 条数据`,
    }

    const paginationConfig1 = {
        current: ipage,
        total: itotal,
        pageSize: 5,
        onChange: (page: number, pageSize?: number) => {
            setIPage(page);
        },
        showTotal: (total: number, range: [number, number]) => `共 ${total} 条数据`,
    }

    return (
        <div className={styles.container}>
            <div className={styles.header}>
                <Select style={{ width: 200 }}
                    onChange={handleChange}
                    defaultValue="2024"
                    options={[
                        { value: '2024', label: '2024' },
                        { value: '2023', label: '2023' },
                        { value: '2022', label: '2022' },
                    ]}
                />
            </div>
            <div >
                <div className={styles.charts} id='main'></div>
            </div>
            <Select style={{ width: 200, marginLeft: 30, marginBottom: 30 }}
                onChange={handleTableChange}
                defaultValue="支出"
                options={[
                    { value: '支出', label: '支出' },
                    { value: '收入', label: '收入' },
                ]}
            />
            {
                type == '支出' ?
                    <Table columns={outcolumns} dataSource={outdata} pagination={paginationConfig}/>
                    : <Table columns={incolumns} dataSource={indata} pagination={paginationConfig1}/>
            }


        </div>
    );
};

export default Container;
